package cn.edu.zust.lxy.wangke_android;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import cn.edu.zust.lxy.wangke_android.util.HttpUtil;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * @author keboom
 * @date 2021/6/14 14:36
 */
public class RegisterActivity extends AppCompatActivity {

    private EditText username;
    private EditText password;
    private EditText phoneNum;
    private Button btn_register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        username = findViewById(R.id.register_username);
        password = findViewById(R.id.register_password);
        phoneNum = findViewById(R.id.register_phoneNum);
        btn_register = findViewById(R.id.register);
        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

    }

    private void register() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject obj = new JSONObject();
                    obj.put("user_name", username.getText().toString());
                    obj.put("user_password", password.getText().toString());
                    obj.put("user_phoneNum", phoneNum.getText().toString());
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(HttpUtil.baseurl + "/user/register")
                            .post(RequestBody.create(MediaType.parse("application/json"), obj.toString()))
                            .build();
                    Response re = client.newCall(request).execute();
                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(RegisterActivity.this, "网络请求失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        }).start();
    }
}
